<template>
	<view>
		<nav-bar title="微信授权" back></nav-bar>
		<scroller-all-box>
			<view class="container">
				<view class="wechatapp">
					<view class="header">
						<open-data class="" type="userAvatarUrl"></open-data>
					</view>
				</view>
				<view class="auth-title">申请获取以下权限</view>
				<view class="auth-subtitle">获得你的手机号进行注册</view>
				<view class="check-box">
					<checkbox @click='check_contract' :checked='checked' />
					<text class='contract_text' @click='check_contract'>我已阅读并同意用户注册协议及免责申明</text>
					<!-- <text class='contract_text' @click='look_contract({checked:2})'>(详情)</text> -->
				</view>
				<!-- 获取手机号 -->
				<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="is_phone == 0"
					class="login-phone-btn">授权获取手机号</button>
				<button v-if="is_phone == 0" class="goback-phone-btn" @click="go_back">返回首页</button>
				<!-- 获取用户资料 -->
				<button class="login-btn" lang="zh_CN" @click="getUserProfile" v-if="is_phone != 0">授权获取用户信息</button>
				<button class="goback-btn" @click="go_back" v-if="is_phone != 0">返回首页</button>
			</view>
			<view :class="[agm_checked==1?'agm_checked':'']" class="agreement_block">
				<view class='agreement_close' @click='agm_checked1({checked:1})'> X </view>
				<view class='agreement_title_block'>{{title}}</view>
				<view class='agreement_text_block'>
					<rich-text :nodes='data' class='content'></rich-text>
				</view>
			</view>
		</scroller-all-box>
	</view>
</template>

<script>
	const app = getApp();
	export default {
		data() {
			return {
				navHeight: app.globalData.navHeight,
				title: '授权登录',
				time: '获取验证码',
				currentTime: 61,
				phone: '',
				code: '',
				disabled: false,
				checked: false,
				agm_checked: '1',
				is_phone: 0,
				hasUserInfo: false,
				canIUseGetUserProfile: false,
			}
		},
		onLoad() {
			// this.get_customer();
			app.globalData.index_login = 0;
			app.login();
			var _this = this;

			/*app._get('user/get_agreement', {}, function(result) {
				var data = result.data;
				data = data.replace(/<section/g, '<div').replace(/\/section>/g, '/div>');
				data = data.replace(/<table[^>]*>/gi, function(match, capture) {
					return match.replace(/width=\"(.*)\"/gi, '');
				});
				data = data.replace(/\ style="/gi, ' style="max-width: 100%;height:auto!important;');
				data = data.replace(/\<img/gi, '<img style="max-width: 100%!important;height:auto!important;"');
				data = data.replace(/<img[^>]*>/gi, function(match, capture) {
					return match.replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig,
						'style="max-width:100%;height:auto;"') // 替换style
				});
				// if (data.length > 0) {
				// 	wxParse.wxParse('content', 'html', data, _this, 0);
				// }

				_this.title = result.title;
				_this.data = data;
			});*/
		},
		methods: {

			//新版获取用户信息 ：getUserProfile
			getUserProfile() {
				let _this = this;
				if (_this.checked == false) {
					app.showError('请勾选我已阅读并同意本小程序的用户注册协议及免责申明之内容');
					return;
				}  
				// 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
				wx.getUserProfile({
					desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						console.log(res);
						if (res.errMsg !== 'getUserProfile:ok') {
							app.showError('授权失败，请联系客服');
							return false;
						}
						app._post_form('user/set', {
							openid: app.globalData.openid,
							user_info: res.rawData,
							encrypted_data: res.encryptedData,
							iv: res.iv,
							signature: res.signature,
							phone: app.globalData.phone,
							unionid: app.globalData.unionid,
						}, function(result) {
							console.log(result)
							console.log('result,,,,,,,,')
							if (result.code === 1) {
								// 记录user_id
								app.globalData.cid = result.data.id;
								app.globalData.user_info = result.data.details;
								console.log(app.globalData);
								// 跳转回原页面
								let pages = getCurrentPages();
								console.log(pages)
								_this.navigateBack();

							} else {
								app.showError(result.msg);
							}
						}, false, function() {
							uni.hideLoading();
						});
					}
				})
			},
			//返回首页
			go_back() {
				app.globalData.openid = 0;
				app.globalData.login_stat = 0;
				uni.redirectTo({
					url: '/pages/index/index',
				})
			},
			/**
			 * 授权登录
			 */
			getPhoneNumber(e) {
				var _this = this;
				console.log(e.detail.errMsg);
				console.log(e.detail.iv);
				console.log(e.detail.encryptedData);
				if (e.detail.errMsg !== 'getPhoneNumber:ok') {
					app.globalData.openid = 0;
					app.globalData.login_stat = 0;
					uni.reLaunch({
						url: '/pages/tabbar/tabbar'
					})
					return false;
				}
				uni.showLoading({
					title: "授权中...",
					mask: true
				});

				uni.login({
					success: function(res) {
						if (res.code) {
							app._post_form('wx/login', {
								code: res.code,
								iv: e.detail.iv,
								encryptedData: e.detail.encryptedData
							}, function(result) {
								console.log(result);
								var openid = result.openid;
								var session_key = result.session_key;
								app.globalData.openid = openid;
								app.globalData.session_key = session_key;
								app.globalData.phone = result.phone;
								app.globalData.login_stat = 1;
								// 记录user_id
								app.globalData.cid = result.cid;
								// 跳转回原页面
								let pages = getCurrentPages();
								console.log(pages)
								_this.navigateBack();
								
								//_this.is_phone = 1;
							}, false, function() {
								uni.hideLoading();
							});
						} else {
							console.log('获取用户手机失败！' + res.errMsg)
						}
					}
				});
			},


			wxLogin() {
				return new Promise(function(reslove, reject) {
					uni.login({
						success(res) {
							reslove(res.code);
						}
					})
				})
			},
			//获取unionid
			unionid: function() {
				var _this = this;
				console.log('3333444  unnionid')
				_this._post_form('wx/unionid', {
					cid: app.globalData.cid,
					uid: app.globalData.uid,
					session_key: app.globalData.session_key,

				}, function(result) {});
			},

			//保存文本框内容
			set_value: function(e) {
				var datatype = e.target.dataset.type;
				var value = e.detail.value;
				switch (datatype) {
					case 'phone':
						// this.setData({
						//   phone: value,
						// })
						this.phone = value;
						break;
					case 'code':
						// this.setData({
						//   code: value,
						// })
						this.code = value;
						break;
				}
			},

			/**
			 * 授权成功 跳转回原页面
			 */
			navigateBack: function() {
				//wx.navigateBack();
				let currentPage = uni.getStorage('currentPage');
				console.log(currentPage)
				var route = '';
				if (typeof(currentPage.route) == "undefined") {
					route = 'pages/index/index';
				} else {
					route = currentPage.route;
				}
				console.log('/' + route + '?' + app.urlEncode(currentPage.options));
				if (route == 'pages/near/near' || route == 'pages/index/index' || route == 'pages/person/person' ||
					route ==
					'pages/discover/discover') {
					uni.redirectTo({
						url: '/' + route
					});
				} else {
					uni.redirectTo({
						url: '/' + route + '?' + app.urlEncode(currentPage.options)
					});
				}
				// wx.redirectTo({
				//   url: '/pages/coupon/coupon'
				//   });
			},

			getCode: function(options) {
				var that = this;
				var currentTime = that.data.currentTime
				interval = setInterval(function() {
					currentTime--;
					// that.setData({
					//   time: currentTime + '秒'
					// })
					that.time = currentTime + '秒'
					if (currentTime <= 0) {
						clearInterval(interval)
						// that.setData({
						//   time: '重新发送',
						//   currentTime: 61,
						//   disabled: false
						// })
						that.time = '重新发送';
						that.currentTime = 61;
						that.disabled = false;
					}
				}, 1000)
			},
			getVerificationCode() {
				let _this = this;
				if (_this.data.disabled == false) {
					var phone = _this.data.phone;
					if (phone == '') {
						uni.showToast({
							title: '请输入手机号',
							icon: "none",
							mask: true,
							duration: 1500,
						})
						return false;
					}
					// _this.setData({
					//   disabled: true,
					// })
					_this.disabled = true;
					app._get('Sms/getcode', {
						phone: phone
					}, function(result) {
						uni.showToast({
							title: '发送成功',
							icon: "none",
							mask: true,
							duration: 1500,
						})
						//console.log(result);
						_this.getCode();
						// _this.setData({
						//   disabled: true,
						//   get_code: result.data
						// })
						_this.disabled = true;
						_this.get_code = result.data;
					});
				}

			},
			check_contract: function() {
				let _this = this;
				if (_this.data.checked) {
					// _this.setData({
					//   checked: false
					// });
					_this.checked = false;
				} else {
					// _this.setData({
					//   checked: true
					// });
					_this.checked = true;
				}
			},
			look_contract: function(e) {
				console.log(e)
				let _this = this;
				var agm_checked = e.checked;
				console.log(_this.data)
				_this.checked = true;
				_this.agm_checked = agm_checked;
			},
			agm_checked1: function(e) {
				var agm_checked = e.checked; //获取当前点击的下标KEY

				// this.setData({
				//   agm_checked: agm_checked, //赋值给data：sub_checked
				// })
				this.agm_checked = agm_checked;
			},
			onShareAppMessage: function() {
				var title = this.data.mainItem.title;
				console.log(title)
				return {
					title: title,
				}
			},
			onShareTimeline: function() {
				var title = this.data.mainItem.title;
				return {
					title: title,
				}
			},

		}
	}
</script>

<style scoped>
	page {
		background: #fff;
		font-size: 32rpx;
	}

	.container {
		padding: 0 60rpx;
	}

	.wechatapp {
		padding: 80rpx 0 48rpx;
		border-bottom: 1rpx solid #e3e3e3;
		text-align: center;
	}

	.wechatapp .header {
		width: 190rpx;
		height: 190rpx;
		border: 2px solid #fff;
		margin: 0rpx auto 0;
		border-radius: 50%;
		overflow: hidden;
		box-shadow: 1px 0px 5px rgba(50, 50, 50, 0.3);
	}

	.auth-title {
		margin-top: 102rpx;
		color: #585858;
		font-size: 40rpx;
		margin-bottom: 40rpx;
		clear: both;
	}

	.auth-subtitle {
		color: #888;
		margin-bottom: 40rpx;
	}

	.check-box {
		margin-bottom: 150rpx;
	}

	checkbox .wx-checkbox-input {
		width: 36rpx;
		/* 背景的宽 */
		height: 36rpx;
		/* 背景的高 */
	}

	.contract_text {
		color: #999999;
		font-size: 28rpx;
	}

	.goback-btn {
		width: 100%;
		border: none;
		height: 88rpx;
		line-height: 88rpx;
		background: #5e6773;
		color: #fff;
		font-size: 11pt;
		border-radius: 999rpx;
		top: 10rpx;
	}

	.goback-phone-btn {
		width: 100%;
		border: none;
		height: 88rpx;
		line-height: 88rpx;
		background: #5e6773;
		color: #fff;
		font-size: 11pt;
		border-radius: 999rpx;
		top: 10rpx;
	}

	.login-phone-btn {
		width: 100%;
		border: none;
		height: 88rpx;
		line-height: 88rpx;
		background: #ff9817;
		color: #fff;
		font-size: 11pt;
		border-radius: 999rpx;
	}

	.login-btn {
		width: 100%;
		border: none;
		height: 88rpx;
		line-height: 88rpx;
		background: #ff5722;
		color: #fff;
		font-size: 11pt;
		border-radius: 999rpx;
	}

	.login-btn::after {
		display: none;
	}

	.login-btn.button-hover {
		box-shadow: inset 0 5rpx 30rpx rgba(0, 0, 0, 0.15);
	}

	.phone,
	.code {
		border-bottom: 1px solid #EEE;
		width: 100%;
		height: 50px;
	}

	.title {
		float: left;
		width: 50px;
		line-height: 45px;
	}

	input {
		float: left;
		width: calc(750rpx - 150px);
		height: 50px;
		line-height: 50px;
	}

	.code .getcode {
		position: absolute;
		right: 0;
		padding-left: 10px;
		margin-right: 10px;
		height: 50px;
		line-height: 50px;
		font-size: 12px;
		border-left: 1px solid #EEE;
	}

	i {
		color: #ef3f3c;
		margin: 10rpx;
	}

	.agreement_block {
		position: fixed;
		top: 0;
		width: 100%;
		height: 100%;
		background: #fff;
		z-index: 99999;
		color: #000;
		overflow: auto;
	}

	.agm_checked {
		display: none;
	}

	.agreement_close {
		padding: 30rpx 30rpx 0;
		text-align: right;
	}

	.agreement_close image {
		width: 60rpx;
		height: 60rpx;
	}

	.agreement_title_block {
		text-align: center;
		color: #000
	}

	.agreement_text_block {
		font-size: 32rpx;
		text-align: justify;
		padding: 36rpx;
		line-height: 60rpx;
	}
</style>
